<!-- src/views/CommunityView.vue -->
<template>
    <div id="app">
      <AppNavbar />

      <div class="community-container">
        <div class="header">
          <h1>社区论坛</h1>
          <button class="publish-btn" @click="goToPublish">发布帖子</button>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-container">
          <div class="filter-row">
            <div class="filter-item">
              <label for="searchQuery">关键词搜索</label>
              <input
                id="searchQuery"
                v-model="searchParams.q"
                type="text"
                placeholder="请输入关键词"
                class="filter-input"
                @keyup.enter="searchPosts"
              />
            </div>

            <div class="filter-item">
              <label for="sortType">排序方式</label>
              <select
                id="sortType"
                v-model="searchParams.sort"
                class="filter-select"
              >
                <option value="updateTime">更新时间</option>
                <option value="heat">热度</option>
              </select>
            </div>

            <div class="filter-item">
              <label for="categoryId">帖子类型</label>
              <select
                id="categoryId"
                v-model="searchParams.categoryId"
                class="filter-select"
              >
                <option value="">全部类型</option>
                <option
                  v-for="category in categoryList"
                  :key="category.categoryId"
                  :value="category.categoryId"
                >
                  {{ category.categoryName }}
                </option>
              </select>
            </div>

            <div class="filter-buttons">
              <button class="search-btn" @click="searchPosts">搜索</button>
              <button class="reset-btn" @click="resetFilters">重置</button>
            </div>
          </div>
        </div>

        <!-- 帖子列表 -->
        <div
          class="post-list"
          ref="postListContainer"
          @scroll="handleScroll"
        >
          <div
            v-for="post in postList"
            :key="post.postId"
            class="post-item"
          >
            <!-- 发布者信息 -->
            <div class="post-author">
              <img
                :src="post.avatarPath"
                :alt="post.nickname"
                class="author-avatar"
                @error="handleImageError"
              />
              <div class="author-info">
                <span class="author-name">{{ post.nickname }}</span>
                <span class="post-time">{{ formatUpdateTime(post.updateTime) }}</span>
              </div>
            </div>

            <!-- 帖子内容 -->
            <div class="post-content" @click="viewPostDetail(post.postId)">
              <div class="post-header">
                <span class="post-category">{{ post.categoryName }}</span>
                <h2 class="post-title">{{ post.title }}</h2>
              </div>
              <p class="post-summary">
                {{ post.content }}
                <span v-if="post.content.length >= 50" class="full-text-btn">全文</span>
              </p>
            </div>

            <!-- 帖子互动 -->
            <div class="post-interactions">
              <div class="interaction-item like"
                   :class="{ active: post.reactionType === 'like' }"
                   @click="handleLike(post)">
                <i class="iconfont icon-like"></i>
                <span>{{ post.likeCount }}</span>
              </div>

              <div class="interaction-item dislike"
                   :class="{ active: post.reactionType === 'dislike' }"
                   @click="handleDislike(post)">
                <i class="iconfont icon-dislike"></i>
              </div>

              <div class="interaction-item comment" @click="viewPostDetail(post.postId)">
                <i class="iconfont icon-pinglun"></i>
                <span>{{ post.replyCount }}</span>
              </div>

              <div class="interaction-item favorite"
                   :class="{ active: post.isFavourite }"
                   @click="handleFavorite(post)">
                <i class="iconfont icon-shoucang_2"></i>
                <span>{{ post.favouriteCount }}</span>
              </div>
            </div>
          </div>

          <!-- 加载更多提示 -->
          <div v-if="loadingMore" class="loading-more">
            加载中...
          </div>

          <div v-if="postList.length === 0 && !loadingMore" class="empty-state">
            <p>暂无符合条件的帖子</p>
          </div>

          <div v-if="noMoreData && postList.length > 0" class="no-more-data">
            没有更多数据了
          </div>
        </div>
      </div>
    </div>
  </template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import AppNavbar from '../components/AppNavbar.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'CommunityView',
  components: {
    AppNavbar
  },
  setup () {
    const postList = ref([])
    const categoryList = ref([])
    const router = useRouter()
    const loadingMore = ref(false)
    const noMoreData = ref(false)
    const postListContainer = ref(null)

    const searchParams = ref({
      q: '',
      sort: 'updateTime',
      categoryId: ''
    })

    onMounted(() => {
      fetchCategoryList()
      fetchPostList()

      // 添加滚动事件监听
      nextTick(() => {
        if (postListContainer.value) {
          postListContainer.value.addEventListener('scroll', handleScroll)
        }
      })
    })

    const goToPublish = () => {
      router.push('/community/publish')
    }

    const fetchCategoryList = async () => {
      try {
        const response = await apiClient.get('/community/getCategoryList')
        if (response.data.code === '200') {
          categoryList.value = response.data.data
        } else {
          console.error('获取帖子类型列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求帖子类型列表出错:', error)
      }
    }

    const fetchPostList = async (isLoadMore = false) => {
      // 如果是加载更多且已经没有更多数据，则直接返回
      if (isLoadMore && noMoreData.value) return

      try {
        // 设置加载状态
        if (isLoadMore) {
          loadingMore.value = true
        }

        // 构建参数对象，确保所有参数都传递给后端
        const params = {
          q: searchParams.value.q, // 即使为空字符串也要传递
          sort: searchParams.value.sort,
          categoryId: searchParams.value.categoryId || '', // 确保传递空字符串而不是null
          offset: isLoadMore ? postList.value.length : 0
        }

        const response = await apiClient.get('/community/getPostList', { params })

        if (response.data.code === '200') {
          if (isLoadMore) {
            // 如果是加载更多，将新数据追加到现有数据后面
            if (response.data.data.length > 0) {
              postList.value = [...postList.value, ...response.data.data]
            } else {
              // 如果没有更多数据，设置标志位
              noMoreData.value = true
            }
          } else {
            // 如果是刷新数据，直接替换
            postList.value = response.data.data
            noMoreData.value = false // 重置无更多数据标志
          }
        } else {
          console.error('获取帖子列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求帖子列表出错:', error)
      } finally {
        if (isLoadMore) {
          loadingMore.value = false
        }
      }
    }

    const formatUpdateTime = (updateTime) => {
      const date = new Date(updateTime)
      const now = new Date()
      const diffTime = Math.abs(now - date)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      if (diffDays === 1) {
        return '今天'
      } else if (diffDays === 2) {
        return '昨天'
      } else if (diffDays <= 7) {
        return `${diffDays - 1}天前`
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }

    const searchPosts = () => {
      // 搜索时重置分页状态
      noMoreData.value = false
      fetchPostList()
    }

    const resetFilters = () => {
      searchParams.value = {
        q: '',
        sort: 'updateTime',
        categoryId: ''
      }
      noMoreData.value = false
      fetchPostList()
    }

    const viewPostDetail = (postId) => {
      router.push({ name: 'PostDetail', params: { postId } })
    }

    const handleLike = async (post) => {
      try {
        let reactionType
        if (post.reactionType === 'like') {
          reactionType = 'cancelLike'
        } else if (post.reactionType === 'dislike') {
          reactionType = 'dislike->like'
        } else {
          reactionType = 'like'
        }

        const response = await apiClient.post('/community/reaction', {
          postId: post.postId,
          reactionType
        })

        if (response.data.code === '200') {
          if (post.reactionType === 'like') {
            // 取消点赞
            post.likeCount--
            post.reactionType = null
          } else if (post.reactionType === 'dislike') {
            // 从点踩转为点赞
            post.likeCount++ // 增加点赞数
            post.reactionType = 'like'
          } else {
            // 从未点赞状态转为点赞
            post.likeCount++
            post.reactionType = 'like'
          }
        }
      } catch (error) {
        console.error('点赞操作失败:', error)
      }
    }

    const handleDislike = async (post) => {
      try {
        let reactionType
        if (post.reactionType === 'dislike') {
          reactionType = 'cancelDislike'
        } else if (post.reactionType === 'like') {
          reactionType = 'like->dislike'
        } else {
          reactionType = 'dislike'
        }

        const response = await apiClient.post('/community/reaction', {
          postId: post.postId,
          reactionType
        })

        if (response.data.code === '200') {
          if (post.reactionType === 'dislike') {
            // 取消点踩
            post.reactionType = null
          } else if (post.reactionType === 'like') {
            // 从点赞转为点踩
            post.likeCount-- // 减少点赞数
            post.reactionType = 'dislike'
          } else {
            // 从未点踩状态转为点踩
            post.reactionType = 'dislike'
          }
        }
      } catch (error) {
        console.error('点踩操作失败:', error)
      }
    }

    const handleFavorite = async (post) => {
      try {
        // 根据当前状态决定要发送的 reactionType
        const reactionType = post.isFavourite ? 'cancel' : 'favorite'

        const response = await apiClient.post('/community/favorite', {
          postId: post.postId,
          reactionType
        })

        if (response.data.code === '200') {
          if (post.isFavourite) {
            post.favouriteCount--
            post.isFavourite = false
          } else {
            post.favouriteCount++
            post.isFavourite = true
          }
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
      }
    }

    const handleImageError = (e) => {
      e.target.src = 'https://photo.fanya.chaoxing.com/photo_80.jpg'
    }

    // 处理滚动事件
    const handleScroll = () => {
      if (!postListContainer.value || loadingMore.value || noMoreData.value) return

      const { scrollTop, scrollHeight, clientHeight } = postListContainer.value
      // 当滚动到底部附近时加载更多
      if (scrollTop + clientHeight >= scrollHeight - 10) {
        fetchPostList(true) // 加载更多数据
      }
    }

    return {
      goToPublish,
      postList,
      categoryList,
      searchParams,
      loadingMore,
      noMoreData,
      postListContainer,
      formatUpdateTime,
      searchPosts,
      resetFilters,
      viewPostDetail,
      handleLike,
      handleDislike,
      handleFavorite,
      handleImageError,
      handleScroll
    }
  }
}
</script>

  <style scoped>
  @import '//at.alicdn.com/t/c/font_5004955_4kt128cmqdu.css';

  #app {
    background: linear-gradient(to right, #e0f7fa, #ffffff);
    min-height: 100vh;
    padding: 20px;
  }

  .community-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}
.publish-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}
.publish-btn:hover {
  background-color: #40a9ff;
}

  .header h1 {
    color: #1890ff;
    margin: 0;
  }

  .filter-container {
    background: white;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: end;
  }

  .filter-item {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-width: 150px;
  }

  .filter-item label {
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
  }

  .filter-input,
  .filter-select {
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 14px;
    transition: all 0.3s;
  }

  .filter-input:focus,
  .filter-select:focus {
    border-color: #1890ff;
    outline: 0;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  .filter-buttons {
    display: flex;
    gap: 10px;
    margin-bottom: 1px;
  }

  .search-btn,
  .reset-btn {
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
    white-space: nowrap;
  }

  .search-btn {
    background-color: #1890ff;
    color: white;
    border: 1px solid #1890ff;
  }

  .search-btn:hover {
    background-color: #40a9ff;
    border-color: #40a9ff;
  }

  .reset-btn {
    background-color: #fff;
    color: #1890ff;
    border: 1px solid #1890ff;
  }

  .reset-btn:hover {
    background-color: #e6f7ff;
  }

  .post-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
    max-height: calc(100vh - 250px);
    overflow-y: auto;
    padding: 10px;
  }

  .post-item {
    display: flex;
    flex-direction: column;
    padding: 20px;
    background: white;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s;
  }

  .post-item:hover {
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
  }

  .post-author {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }

  .author-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 12px;
  }

  .author-info {
    display: flex;
    flex-direction: column;
  }

  .author-name {
    font-weight: 500;
    color: #333;
  }

  .post-time {
    font-size: 12px;
    color: #999;
  }

  .post-content {
    cursor: pointer;
    margin-bottom: 15px;
  }

  .post-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .post-category {
    background-color: #e6f7ff;
    color: #1890ff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    margin-right: 10px;
  }

  .post-title {
    margin: 0;
    color: #333;
    font-size: 18px;
  }

  .post-summary {
    color: #666;
    line-height: 1.5;
    margin: 0;
    text-align: left;
  }

  .full-text-btn {
    color: #1890ff;
    cursor: pointer;
    margin-left: 5px;
  }

  .post-interactions {
    display: flex;
    gap: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
  }

  .interaction-item {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    color: #999;
    transition: color 0.3s;
  }

  .interaction-item:hover {
    color: #1890ff;
  }

  .interaction-item.active {
    color: #1890ff;
  }

  .interaction-item.like.active {
    color: #ff4d4f;
  }

  .interaction-item.dislike.active {
    color: #1890ff;
  }

  .interaction-item.favorite.active {
    color: #ffcc00;
  }

  .empty-state {
    text-align: center;
    padding: 40px;
    background: white;
    border-radius: 8px;
    color: #999;
  }

  .loading-more,
  .no-more-data {
    text-align: center;
    padding: 20px;
    color: #999;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .filter-row {
      flex-direction: column;
      align-items: stretch;
    }

    .filter-item {
      min-width: auto;
    }

    .post-interactions {
      justify-content: space-around;
    }
  }
  </style>
